if (typeof console == "undefined") {
    this.console = {
        log: function (msg) {}
    };
}
// 如果浏览器不支持websocket，会使用这个flash自动模拟websocket协议，此过程对开发者透明
WEB_SOCKET_SWF_LOCATION = "/swf/WebSocketMain.swf";
// 开启flash的websocket debug
WEB_SOCKET_DEBUG = true;
var ws;

// 连接服务端
function connect() {
    // 创建websocket
    ws = new WebSocket("ws://" + document.domain + ":7273");
    ws.onopen = function () {
        console.log("websocket握手成功，登录");
        onSend({
            'type': 'login'
        });
        setInterval(function () {
            onSend({
                'type': 'location'
            });
        }, 10000);
    };
    ws.onmessage = onmessage;
    ws.onclose = function () {
        console.log("连接关闭，定时重连");
        connect();
    };
    ws.onerror = function () {
        console.log("出现错误");
    };
}

// 服务端发来消息时
function onmessage(e) {
    console.log('recv:' + e.data);
    var data = JSON.parse(e.data);
    switch (data['type']) {
        // 服务端ping客户端
        case 'ping':
            onSend({
                'type': "pong"
            });
            break;
        case 'login':
            console.log(data['client_name'] + " 登录");
            onSend({
                'type': 'location'
            });
            break;
        case 'logout':
            console.log(data['client_name'] + " 退出");
            break;
        case 'oilOff':
            if (data['result'] == 'true') {
                alert('断油电成功');
            } else {
                alert('断油电失败');
            }
            break;
        case 'oilOn':
            if (data['result'] == 'true') {
                alert('通油电成功');
            } else {
                alert('通油电失败');
            }
            break;
        case 'verno':
            if (data['data']) {
                //$('#result').attr('value') = data['data'];
            }
            break;
        case 'location':
            var lat = data['lat'] / 1000000.0;
            var lon = data['lon'] / 1000000.0;
            //map.panTo(new BMap.Point(lon, lat));
            //addMarker(currDevId, lat, lon, currDevId, "当前位置<br>经度：" + lon + "<br>纬度：" + lat);
            break;
    }
}

var currDevId;

function onSend(d) {
    if (query.devId.value == "") {
        query.devId.focus();
        return false;
    }
    d['devId'] = query.devId.value;
    currDevId = query.devId.value;
    console.log('send:' + JSON.stringify(d));
    ws.send(JSON.stringify(d));
}

function moduleCtrlClick(type) {
    if (query.devId.value == "") {
        alert("请输入项目ID");
        query.devId.focus();
        return false;
    }
    onSend({
        'type': type
    });
}